package com.lswms.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ZqDateUtil {

	private static final Logger Logger = LoggerFactory.getLogger(ZqDateUtil.class);

	static final DateTimeFormatter shortFMT = DateTimeFormat.forPattern("yyyyMMdd");

	static final DateTimeFormatter HHmm = DateTimeFormat.forPattern("HHmm");

	static final DateTimeFormatter shortFMTHalfed = DateTimeFormat.forPattern("yyyy-MM-dd");

	static final DateTimeFormatter fullFMT = DateTimeFormat.forPattern("yyyyMMddHHmmss");

	static final DateTimeFormatter shortFMTHalfedhms = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

	public static final Date getNow() {
		return new DateTime().toDate();
	}

	public static final Date getDatehms(String yyyyMMdd) {
		return shortFMTHalfedhms.parseDateTime(yyyyMMdd).toDate();
	}

	public static final Date getDate(String yyyyMMdd) {
		Date date = null;
		try {
			date = shortFMT.parseDateTime(yyyyMMdd).toDate();
		} catch (Exception e) {

		} finally {
			//
		}
		return date;
	}

	public static final Date getDateHalfed(String yyyyMMdd) {
		Date date = null;
		try {
			date = shortFMTHalfed.parseDateTime(yyyyMMdd).toDate();
		} catch (Exception e) {
			Logger.error(e.getMessage(), e);
		} finally {
			//
		}
		return date;
	}

	public static final String yyyyMMddHHmmssSSS() {
		return new DateTime(new Date()).toString("yyyy-MM-dd HH:mm:ss.SSS");
	}

	public static final String yyyyMMddHHmmssSSSHl() {
		return new DateTime(new Date()).toString("yyyyMMddHHmmssSSS");
	}

	public static final String yyyyMMddHHmm() {
		return new DateTime(new Date()).toString("yyyy-MM-dd HH:mm");
	}

	public static final String HHmm() {
		return new DateTime(new Date()).toString("HHmm");
	}

	public static final String yyyyMMddHHmmss(Date date) {
		return new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
	}

	public static final String yyyyMMddHHmm(Date date) {
		return new DateTime(date).toString("yyyy-MM-dd HH:mm");
	}

	public static final String yyyyMMdd(Date date) {
		return new DateTime(date).toString("yyyyMMdd");
	}

	public static final String yyyy_MM_dd(Date date) {
		return new DateTime(date).toString("yyyy-MM-dd");
	}
	public static final String MM_dd(Date date) {
		return new DateTime(date).toString("MM-dd");
	}

	public static final String HHmmss(Date date) {
		return new DateTime(date).toString("HHmmss");
	}

	public static final String Hms(Date date) {
		return new DateTime(date).toString("HH:mm:ss");
	}

	public static final String yyyyMMddHalfed(Date date) {
		return new DateTime(date).toString("yyyy-MM-dd");
	}

	public static final String yyyyMMddFull(Date date) {
		return new DateTime(date).toString("yyyy年MM月dd日");
	}

	/**
	 * 计算两个日期相差的天数
	 * 
	 * @param paramDate
	 * @return
	 */
	public static int compareDate(Date date1, Date date2) {
		String date3 = yyyyMMdd(date1);
		String date4 = yyyyMMdd(date2);
		return Math.abs(Days.daysBetween(new DateTime(getDate(date3)), new DateTime(getDate(date4))).getDays());
	}

	public static final int get8HourDate(Date date) {
		return new DateTime(date).getHourOfDay();
	}

	public static String getCurrentTime() {
		Date now = new Date();
		SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String retValue = sdf_time.format(now);
		return retValue;
	}

	public static String getFileName() {
		Date now = new Date();
		SimpleDateFormat sdf_filename = new SimpleDateFormat("yyyyMMdd.HHmm");
		String retValue = sdf_filename.format(now);
		return retValue;
	}

	public static String formatDate(Date date, SimpleDateFormat f) {
		if (date == null) {
			return null;
		} else {
			return f.format(date);
		}
	}

	public static Date parseDate(String date, SimpleDateFormat f) {
		if (date == null) {
			return null;
		} else {
			try {
				return f.parse(date);
			} catch (ParseException e) {
				//
				System.out.println("" + e.getMessage());
			}
			return null;
		}
	}

	/**
	 * 日期加减
	 * 
	 * @param date
	 *            原日期
	 * @param i
	 *            加减值
	 * @param n
	 *            Calendar.YEAR Calendar.MONTH Calendar.DAY_OF_MONTH
	 * @return
	 */
	public static Date addDate(Date date, int i, int n) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(n, i);
		date = calendar.getTime();
		return date;
	}

	public static Date nextDay(String dateStr) {
		Date dt = null;
		try {
			dt = shortFMT.parseDateTime(dateStr).toDate();
		} catch (Exception e) {
			Logger.error(e.getMessage(), e);
		} finally {
			//
		}
		if (dt != null) {
			return new DateTime(dt).plusDays(1).toDate();
		} else {
			return dt;
		}
	}

	public static Date frontDay(String dateStr) {
		Date dt = null;
		try {
			dt = shortFMT.parseDateTime(dateStr).toDate();
		} catch (Exception e) {
			Logger.error(e.getMessage(), e);
		} finally {
			//
		}
		if (dt != null) {
			return new DateTime(dt).minusDays(1).toDate();
		} else {
			return dt;
		}
	}

	public static String frontDay(Date date, int count) {
		return new DateTime(date).minusDays(count).toString("yyyy-MM-dd");
	}

	public static String addDays(Date date, int count) {
		return new DateTime(date).plusDays(count).toString("yyyy-MM-dd");
	}

	public static String addMonths(Date date, int count) {
		return new DateTime(date).plusMonths(count).toString("yyyy-MM-dd");
	}

	public static String addMonthsYM(Date date, int count) {
		return new DateTime(date).plusMonths(count).toString("yyyy-MM");
	}

	public static String addDaysHMS(Date date, int count) {
		return new DateTime(date).plusDays(count).toString("yyyy-MM-dd HH:mm:ss");
	}

	public static String addMonthsHMS(Date date, int count) {
		return new DateTime(date).plusMonths(count).toString("yyyy-MM-dd HH:mm:ss");
	}

	public static int getDays(Date beginDate, Date endDate) {
		DateTime beginTime = new DateTime(beginDate);
		DateTime endTime = new DateTime(endDate);
		return (int) new Duration(beginTime, endTime).getStandardDays();
	}

	public static String getRestTime(Date beginTime, int count, String timeUnit) {
		DateTime begin = new DateTime(new Date());
		DateTime end = null;
		if ("D".equals(timeUnit)) {
			end = new DateTime(addDays(beginTime, count));
		} else if ("M".equals(timeUnit)) {
			end = new DateTime(addMonths(beginTime, count));
		}
		long minutes = new Duration(begin, end).getStandardMinutes();
		long days = minutes / 1440;// 天
		long daysMod = minutes % 1440;// 余数
		long hours = daysMod / 60;// 小时
		String reMainStr = null;
		if (days > 0) {
			reMainStr = days + "天";
		} else {
			reMainStr = hours + "小时";
		}
		return reMainStr;
	}

	/**
	 * 得到指定月份的第一天和最后一天
	 * 
	 * @param year
	 *            年
	 * @param month
	 *            月
	 * @return 第一天,最后一天
	 */
	public static String[] getMonthDay(int year, int monthOfYear) {
		String[] days = new String[2];

		DateTime dateTime = new DateTime(year, monthOfYear, 1, 1, 1);
		String minDay = dateTime.dayOfMonth().withMinimumValue().toString("yyyy-MM-dd");
		String maxDay = dateTime.dayOfMonth().withMaximumValue().toString("yyyy-MM-dd");
		days[0] = minDay;
		days[1] = maxDay;

		return days;
	}

	public static final String yyyy_MM() {
		return new DateTime(new Date()).toString("yyyy-MM");
	}

	/**
	 * 将日期转为自然日(eg:2016-08-05 18:11:20=====>2016-08-05 00:00:00)
	 * 
	 * @param date
	 *            日期
	 * @param sdf
	 *            日期格式化器
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static final Date parseDate2NaturalDay(Date date, SimpleDateFormat sdf) {
		try {
			return sdf.parse(sdf.format(date));
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("时间:{" + date.toLocaleString() + "}格式解析异常");
		}
	}

	/**
	 * 日期之间的比较(默认是比较当前日期,eg:2016-12-10<=2017-02-11<2017-02-12======> true)
	 * 
	 * @param minDate
	 *            最小日期
	 * @param compareDate
	 *            比较日期
	 * @param maxDate
	 *            最大日期
	 * @return
	 */
	/*
	 * public static final boolean comparedDate(Date minDate, Date compareDate,
	 * Date maxDate) { if (minDate == null && maxDate == null) { return false; }
	 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); if
	 * (compareDate == null) { compareDate = parseDate2NaturalDay(new Date(),
	 * sdf); } // 如果最小时间为空,判断比较日期是否超过最大日期 if (minDate == null) { return
	 * compareDate.compareTo(maxDate) >= 0; } // 如果最大日期为空,判断比较日期是否在小于最小日期 if
	 * (maxDate == null) { return compareDate.compareTo(minDate) <= 0; } //
	 * 判断比较时间是否在minDate<=compareDate<maxDate之间 return
	 * compareDate.compareTo(minDate) >= 0 && compareDate.compareTo(maxDate) <
	 * 0; }
	 */
	/**
	 * 日期之间的比较(默认是比较当前日期,eg:2016-12-10<=2017-02-11<2017-02-12======> true)
	 * 
	 * @param minDate
	 *            最小日期
	 * @param compareDate
	 *            比较日期
	 * @param maxDate
	 *            最大日期
	 * @return
	 */
	public static final boolean comparedDate(Date minDate, Date compareDate, Date maxDate) {
		if (minDate == null && maxDate == null) {
			return false;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (compareDate == null) {
			compareDate = parseDate2NaturalDay(new Date(), sdf);
		}
		// 如果最小时间为空,判断比较日期是否超过最大日期
		if (minDate == null) {
			return compareDate.compareTo(maxDate) >= 0;
		}
		// 如果最大日期为空,判断比较日期是否在小于最小日期
		if (maxDate == null) {
			return compareDate.compareTo(minDate) <= 0;
		}
		// 判断比较时间是否在minDate<=compareDate<maxDate之间
		return compareDate.compareTo(minDate) > 0 && compareDate.compareTo(maxDate) <= 0;
	}

	/**
	 * 比较两个时间大小 去除时分秒
	 * 
	 * @param firstDate
	 * @param secondDate
	 * @return
	 */
	public static final int compareTwoDate(Date firstDate, Date secondDate) {
		firstDate = paramsDate(firstDate);
		secondDate = paramsDate(secondDate);
		return firstDate.compareTo(secondDate);
	}

	public static final Date paramsDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String format = sdf.format(date);
		try {
			date = sdf.parse(format);
		} catch (ParseException e) {
		}
		return date;
	}

	/**
	 * 比较三个时间 加时分秒
	 * 
	 * @param minDate
	 * @param currentDate
	 * @param maxDate
	 * @return
	 */
	public static final boolean compareThreeTime(Date minDate, Date currentDate, Date maxDate) {

		if (minDate.compareTo(currentDate) < 0 && maxDate.compareTo(currentDate) > 0) {

			return true;
		}

		return false;
	}

	/**
	 * 获取今天开始时间 如: 2016-08-13 00:00:00
	 * 
	 * @return
	 */
	public static final Date getTodayStartDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date time = calendar.getTime();
		return time;
	}

	/**
	 * 获取当天开始时间加30分钟
	 * 
	 * @return
	 */
	public static final Date getTodayStartDateAddTenMinute() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 30);
		calendar.set(Calendar.SECOND, 0);
		Date time = calendar.getTime();
		return time;
	}

	public static final Date getDateByhhmmss(String hhmmss) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date preDate = sdf.parse(yyyy_MM_dd(new Date()) + " " + hhmmss);
		return preDate;
	}

	/**
	 * 获取指定时间,如果解析时间失败，则返回当前时间
	 * 
	 * @param dateStr
	 * @return
	 */
	public static final Date formatDateTime(String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date datetime = null;
		try {
			datetime = sdf.parse(dateStr);
		} catch (ParseException e) {
			datetime = new Date();
		}
		return datetime;
	}
	
	public static final Date paramsDate(String HHmmss) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date parse = null;;
		try {
			parse = sdf.parse(yyyyMMddHalfed(new Date())+" "+HHmmss);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return parse;
	}
	 /**
     * 根据日期获取 星期 （2019-05-06 ——> 星期一）
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = f.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

	public static void main(String[] args) throws Exception {
		/*
		 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date
		 * preDate = sdf.parse("2016-01-01"); Date nowDate =
		 * sdf.parse("2017-08-08"); Date nextDate = sdf.parse("2017-02-01");
		 * boolean result = nowDate.compareTo(preDate) >= 0 &&
		 * nowDate.compareTo(nextDate) < 0; System.out.println(result);
		 */

		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		// Date preDate = sdf.parse(yyyy_MM_dd(new Date())+" 00:08:20");

		// System.out.println(yyyyMMddHHmmss(getDateByhhmmss("00:00:00")));
		// System.out.println(yyyyMMddHHmmss(getDateByhhmmss("00:10:00")));

		// Date formatDateTime = formatDateTime("2030-09-19 12:59:59");
		//
		// Date startRobTime = ZqDateUtil.formatDateTime("2030-09-19 12:59:59");
		// Date formatDateTime2 = formatDateTime("2016-09-19 12:00:00");
		// System.out.println(formatDateTime);
		// System.out.println(formatDateTime2);
		// System.out.println(startRobTime.compareTo(new Date()));
		// System.out.println(getRestTime(new Date(), 10, "D"));
		// System.out.println(compareThreeTime(getTodayStartDate(), preDate,
		// getTodayStartDateAddTenMinute()));

		/*Date date = addDate(new Date(), -7, Calendar.DAY_OF_MONTH);
		System.out.println(date);

		System.out.println(addMonthsYM(new Date(), 3));
		;

		System.out.println(getMonthDay(2017, 1)[0] + "," + getMonthDay(2017, 1)[1]);
		
		
		System.out.println(getDays(
				ZqDateUtil.getDateHalfed("2016-11-02".substring(0, 8) + "01"),
				ZqDateUtil.getDateHalfed(ZqDateUtil.addMonths(
						ZqDateUtil.getDateHalfed("2016-11-02".substring(0, 8)
								+ "01"), 1))));;
*/
								
		System.out.println(ZqDateUtil.frontDay(ZqDateUtil.getNow(),1));
		System.out.println(dateToWeek("2020-06-21"));
		
	}
}
